<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="userTagList" border>
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="标签名称" prop="name" min-width="150" show-overflow-tooltip />
      <el-table-column label="标签描述" prop="description" min-width="200" show-overflow-tooltip />
      <el-table-column label="等级" prop="level" width="100" align="center" />
      <el-table-column label="标签类型" prop="type" width="120" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.type || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="升级条件" min-width="300" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.level_upgrade" class="upgrade-info">
            <div v-if="scope.row.level_upgrade.new_user_count">新增用户: {{ scope.row.level_upgrade.new_user_count }}</div>
            <div v-if="scope.row.level_upgrade.total_new_user_count">总新增用户: {{
              scope.row.level_upgrade.total_new_user_count }}</div>
            <div v-if="scope.row.level_upgrade.total_trade_amount">总交易金额: {{ scope.row.level_upgrade.total_trade_amount
            }}</div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="奖励比例" min-width="200" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.reward_ratio" class="reward-info">
            <div
              v-if="scope.row.reward_ratio.invite_ratio !== undefined && scope.row.reward_ratio.invite_ratio !== null">
              邀请比例: {{ scope.row.reward_ratio.invite_ratio }}%
            </div>
            <div v-if="scope.row.reward_ratio.trade_ratio !== undefined && scope.row.reward_ratio.trade_ratio !== null">
              交易比例: {{ scope.row.reward_ratio.trade_ratio }}%
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at ? parseTime(scope.row.created_at) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入标签描述" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input-number v-model="form.level" :min="0" placeholder="请输入等级" style="width: 100%" />
        </el-form-item>
        <el-form-item label="标签类型" prop="type">
          <el-input-number v-model="form.type" :min="0" placeholder="请输入标签类型" style="width: 100%" />
        </el-form-item>

        <el-divider content-position="left">升级条件</el-divider>
        <el-form-item label="新增用户数量">
          <el-input-number v-model="form.level_upgrade.new_user_count" :min="0" placeholder="请输入新增用户数量"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="总新增用户数量">
          <el-input-number v-model="form.level_upgrade.total_new_user_count" :min="0" placeholder="请输入总新增用户数量"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="总交易金额">
          <el-input-number v-model="form.level_upgrade.total_trade_amount" :min="0" :precision="2"
            placeholder="请输入总交易金额" style="width: 100%" />
        </el-form-item>

        <el-divider content-position="left">奖励比例</el-divider>
        <el-form-item label="邀请比例(%)">
          <el-input-number v-model="form.reward_ratio.invite_ratio" :min="0" :precision="2" placeholder="请输入邀请比例"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="交易比例(%)">
          <el-input-number v-model="form.reward_ratio.trade_ratio" :min="0" :precision="2" placeholder="请输入交易比例"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserTagList, addUserTag } from '@/api/api'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'UserTag',
  data() {
    return {
      loading: false,
      submitLoading: false,
      showSearch: true,
      userTagList: [],
      total: 0,
      title: '',
      open: false,
      queryParams: {
        page: 1,
        pageSize: 10
      },
      form: {
        id: undefined,
        name: '',
        description: '',
        level: 0,
        type: 0,
        level_upgrade: {
          new_user_count: 0,
          total_new_user_count: 0,
          total_trade_amount: 0
        },
        reward_ratio: {
          invite_ratio: 0,
          trade_ratio: 0
        }
      },
      rules: {
        name: [
          { required: true, message: '标签名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      const params = {
        page: this.queryParams.page,
        pageSize: this.queryParams.pageSize
      }
      getUserTagList(params)
        .then(res => {
          const { list, total } = this.normalizeResponse(res)
          this.userTagList = list
          this.total = total || list.length
        })
        .finally(() => {
          this.loading = false
        })
    },
    normalizeResponse(res) {
      if (!res) {
        return { list: [], total: 0 }
      }
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }
      if (Array.isArray(res.rows)) {
        return { list: res.rows, total: res.total ?? res.rows.length }
      }
      if (Array.isArray(res.data)) {
        return { list: res.data, total: res.total ?? res.data.length }
      }
      if (res.data && Array.isArray(res.data.records)) {
        return { list: res.data.records, total: res.data.total ?? res.data.records.length }
      }
      if (res.data && Array.isArray(res.data.list)) {
        return { list: res.data.list, total: res.data.total ?? res.data.list.length }
      }
      if (Array.isArray(res.list)) {
        return { list: res.list, total: res.total ?? res.list.length }
      }
      if (Array.isArray(res.records)) {
        return { list: res.records, total: res.total ?? res.records.length }
      }
      return { list: [], total: 0 }
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    reset() {
      this.form = {
        id: undefined,
        name: '',
        description: '',
        level: 0,
        type: 0,
        level_upgrade: {
          new_user_count: 0,
          total_new_user_count: 0,
          total_trade_amount: 0
        },
        reward_ratio: {
          invite_ratio: 0,
          trade_ratio: 0
        }
      }
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增用户标签'
    },
    handleUpdate(row) {
      if (!row || !row.id) {
        this.$modal.msgWarning('请选择要修改的用户标签')
        return
      }
      this.form = {
        id: row.id,
        name: row.name || '',
        description: row.description || '',
        level: row.level !== undefined && row.level !== null ? Number(row.level) : 0,
        type: row.type !== undefined && row.type !== null ? Number(row.type) : 0,
        level_upgrade: {
          new_user_count: row.level_upgrade?.new_user_count || 0,
          total_new_user_count: row.level_upgrade?.total_new_user_count || 0,
          total_trade_amount: row.level_upgrade?.total_trade_amount || 0
        },
        reward_ratio: {
          invite_ratio: row.reward_ratio?.invite_ratio || 0,
          trade_ratio: row.reward_ratio?.trade_ratio || 0
        }
      }
      this.$nextTick(() => {
        if (this.$refs.form && this.$refs.form.clearValidate) {
          this.$refs.form.clearValidate()
        }
      })
      this.open = true
      this.title = '修改用户标签'
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        this.submitLoading = true
        const payload = {
          ...this.form
        }

        const request = payload.id ? addUserTag(payload) : addUserTag({ ...payload, id: undefined })
        request
          .then(() => {
            this.$modal.msgSuccess(payload.id ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    parseTime
  }
}
</script>

<style scoped lang="scss">
.upgrade-info,
.reward-info {
  text-align: left;
  font-size: 12px;
  line-height: 1.6;

  div {
    margin-bottom: 4px;
  }
}
</style>
